<?php
declare(strict_types=1);

namespace App\Logic\User\Service;

use App\Exceptions\DbException;
use App\Library\RedisClient;
use App\Logic\User\Repository\User\AuthorRepository;
use Illuminate\Support\Facades\Cache;
use Throwable;
use function request;

class BaseService
{
    protected function getUserUid(): string
    {
        try {
            $authorization = request()->header("Authorization");
            $authorization = trim(str_replace("Bearer", "", $authorization));
            $userInfo = Cache::get("login:token:" . $authorization);
            if (empty($userInfo)) {
                return "";
            }
            return (string)json_decode($userInfo, true)["uid"];
        } catch (Throwable $throwable) {
            return "";
        }
    }


    protected function updateUserInfo(array $userInfo): bool
    {
        try {
            $authorization = request()->header("Authorization");
            $authorization = trim(str_replace("Bearer", "", $authorization));
            return Cache::put("login:token:" . $authorization, json_encode($userInfo), (7 * 86400) + mt_rand(100, 9999));
        } catch (Throwable $throwable) {
            return false;
        }
    }

    protected function authorUserUid(): string
    {
        $requestParams["user_uid"] = $this->getUserUid();
        $authorRepository = new AuthorRepository();
        $authorInfo = $authorRepository->repositoryFind(function ($query) use ($requestParams) {
            $query->where("user_uid", "=", $requestParams["user_uid"]);
        }, ["uid", "is_forbidden", "profession"]);
        if (empty($authorInfo)) {
            throw new DbException("请先认证为创作者");
        }
        if ($authorInfo["is_forbidden"] == 1) {
            throw new DbException("创作者被禁用");
        }
        return (string)$authorInfo["uid"];
    }
}
